package com.jia.lidao.ui.order;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.jia.lidao.Constans;
import com.jia.lidao.R;
import com.jia.lidao.RunningContext;
import com.jia.lidao.UserUtils;
import com.jia.lidao.enity.PayResponseDTO;
import com.jia.lidao.enity.RefreshStatusMessage;
import com.jia.lidao.enity.WXpayEnity;
import com.jia.lidao.enity.WeiChatPayBeen;
import com.jia.lidao.network.http.BusinessManager;
import com.jia.lidao.network.http.MyCallback;
import com.jia.lidao.network.http.request.impl.DealWithOrderRequest;
import com.jia.lidao.network.http.request.impl.OrderDetailRequest;
import com.jia.lidao.network.http.request.impl.PayRequest;
import com.jia.lidao.others.enity.OrderInfor;
import com.jia.lidao.others.ui.AppraiseActivity;
import com.jia.lidao.others.ui.OrderInforGoodView;
import com.jia.lidao.others.ui.fragment.OrderDetailActivity;
import com.jia.lidao.others.utils.DisplayUtil;
import com.jia.lidao.ui.BaseActivity;
import com.jia.lidao.utils.LogUtil;
import com.jia.lidao.widget.CommonTitleBar;
import com.squareup.picasso.Picasso;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.Map;

import me.nereo.multi_image_selector.bean.Image;

/**
 * Created by jia on 17/12/18.
 */

public class ConfirmOrderActivity extends BaseActivity {

    private CommonTitleBar commonTitleBar;

    private TextView tvOrderNO, tvState, tvTime, tvName, tvAddress, tvShopname, tvPayWay,
            tvPaytime, tvPrice, tvCount, tvTotalmoney, tvFree, tvSend, tvCancel;

    private LinearLayout content;

    private ImageView ivShop, ivNext;

    private int id;

    private int role;

    View line;

    public static ConfirmOrderActivity instance;

    private OrderInfor orderInfor;

    private IWXAPI iwxapi;

    private TextView tvinform;

    private LinearLayout llinform;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        instance = this;
        setContentView(R.layout.activity_confirmorder);
        id = getIntent().getIntExtra("ID", 0);
        role = getIntent().getIntExtra("role", 0);
        iwxapi = WXAPIFactory.createWXAPI(getApplicationContext(), Constans.APP_ID);
        // 将该app注册到微信
        iwxapi.registerApp(Constans.APP_ID);
        initView();
    }

    private void initView() {
        commonTitleBar = (CommonTitleBar) findViewById(R.id.common_title_bar);
        commonTitleBar.setTitle("订单详情");
        tvOrderNO = (TextView) findViewById(R.id.tv_order_NO);
        tvState = (TextView) findViewById(R.id.tv_state);
        tvTime = (TextView) findViewById(R.id.tv_time);
        tvName = (TextView) findViewById(R.id.tv_name);
        tvAddress = (TextView) findViewById(R.id.tv_address);
        ivShop = (ImageView) findViewById(R.id.iv_shop_header);
        tvShopname = (TextView) findViewById(R.id.tv_shop_name);
        tvPayWay = (TextView) findViewById(R.id.tv_pay_way);
        tvPaytime = (TextView) findViewById(R.id.tv_pay_time);
        tvPrice = (TextView) findViewById(R.id.tv_price);
        tvTotalmoney = (TextView) findViewById(R.id.tv_total_money);
        tvFree = (TextView) findViewById(R.id.tv_coupon);
        content = (LinearLayout) findViewById(R.id.ll_goods_content);
        tvSend = (TextView) findViewById(R.id.tv_status_send);
        line = (View) findViewById(R.id.line);
        tvCancel = (TextView) findViewById(R.id.tv_status_cancel);
        tvinform = (TextView) findViewById(R.id.tv_inform);
        llinform = (LinearLayout) findViewById(R.id.informll);
        ivNext = (ImageView) findViewById(R.id.iv_next);


        tvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (orderInfor == null) {
                    showToast("订单信息错误");
                    return;
                }
                if (role == Constans.ORDERRECEIVE) {
                    if (orderInfor.order.status == 3 || orderInfor.order.status == 4) {
                        dealWithOrder(role, orderInfor.order.status, orderInfor.order.id);
                    } else if (orderInfor.order.status == 5) {
                        dismissDialog();
                        startActivity(new Intent(ConfirmOrderActivity.this, AppraiseActivity.class).putExtra("ID", orderInfor.order.id));
                    } else if (orderInfor.order.status == 1) {
                        BusinessManager.getInstance().payOrder(new PayRequest(orderInfor.order.id), new MyCallback<PayResponseDTO>() {
                            @Override
                            public void onSuccess(PayResponseDTO result, String message) {
                                if (result == null)
                                    showToast("获取支付信息失败");
                                dismissDialog();
                                switch (orderInfor.order.payment_type) {
                                    case 1:
                                        doZFBzf(result.alipay);
                                        break;
                                    case 2:
                                        wxPay(result.wechat);
                                        break;
                                    case 3:
                                        dpUPPay(result.unionpay);
                                        break;
                                }
                            }

                            @Override
                            public void onError(String errorCode, String message) {
                                showToast(message);
                                dismissDialog();
                            }

                            @Override
                            public void onFinished() {

                            }

                            @Override
                            public void onRefreshToken() {
                                UserUtils.getInstance().goToLogin(ConfirmOrderActivity.this);
                            }
                        });
                    }

                } else if (role == Constans.ORDERSEND) {
                    if (orderInfor.order.status == 1 || orderInfor.order.status == 4) {
                        dealWithOrder(role, orderInfor.order.status, orderInfor.order.id);
                    } else if (orderInfor.order.status == 3) {
                        dismissDialog();
                        startActivity(new Intent(ConfirmOrderActivity.this, TransportActivity.class).putExtra("ID", orderInfor.order.id));
                    } else if (orderInfor.order.status == 2) {
                        dismissDialog();
                        startActivity(new Intent(ConfirmOrderActivity.this, AuditActivity.class).putExtra("ID", orderInfor.order.id).putExtra("paymenttype", orderInfor.order.payment_type).putExtra("status", orderInfor.order.status).putExtra("role", role).putExtra("remittance", new Gson().toJson(orderInfor.order.remittance)).putExtra("loan", new Gson().toJson(orderInfor.order.loan)));
                    }
                }
            }
        });

        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (orderInfor.order.status == 1) {
                    dealWithOrder(role, 7, orderInfor.order.id);
                } else if (orderInfor.order.status == 6) {
                    dealWithOrder(role, 8, orderInfor.order.id);
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {
        showDialog("");
        BusinessManager.getInstance().getOrderDetail(new OrderDetailRequest(id), new MyCallback<OrderInfor>() {
            @Override
            public void onSuccess(OrderInfor result, String message) {
                if (result != null) {
                    orderInfor = result;
                    tvOrderNO.setText("订单号：" + result.order.order_sn);
                    tvTime.setText("提交时间：" + result.order.getCreated_time());
                    tvState.setText(result.order.getStatus_name());
                    tvName.setText(result.order.address.getConsignee() + " " + result.order.address.getPhone());
                    tvAddress.setText(result.order.address.getProvince_name() + result.order.address.getCity_name() + result.order.address.getCounty_name() + result.order.address.getStreet());
                    if (content.getChildCount() > 0) {
                        content.removeAllViews();
                    }
                    //status：-2已关闭 -1已驳回 1待付款 2待审核 3待发货 4待收货 5待评价 6已完成 ,
                    if (role == Constans.ORDERRECEIVE) {
                        switch (result.order
                                .status) {
                            case 1:
                                tvCancel.setVisibility(View.VISIBLE);
                                tvCancel.setText("取消订单");
                                tvSend.setText("立即付款");
                                break;
                            case 2:
                                tvSend.setVisibility(View.GONE);
                                break;
                            case 3:
                                tvSend.setText("提醒发货");
                                break;
                            case 4:
                                tvSend.setText("确认收货");
                                break;
                            case 5:
                                tvSend.setText("去评价");
                                break;
                            case 6:
                                tvCancel.setVisibility(View.VISIBLE);
                                tvCancel.setText("删除订单");
                                tvSend.setVisibility(View.GONE);
                                break;
                            default:
                                tvSend.setVisibility(View.GONE);
                                break;

                        }
                    } else {
                        switch (orderInfor.order.status) {
                            case 1:
                                tvSend.setText("提醒付款");
                                break;
                            case 2:
                                tvSend.setText("去审核");
                                break;
                            case 3:
                                tvSend.setText("去发货");
                                break;
                            case 4:
                                tvSend.setText("提醒收货");
                                break;
                            default:
                                tvSend.setVisibility(View.GONE);
                                break;
                        }
                    }
                    if (result.order.payment_type == 5 || result.order.payment_type == 6) {
                        tvPayWay.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(new Intent(ConfirmOrderActivity.this, AuditActivity.class).putExtra("ID", orderInfor.order.id).putExtra("paymenttype", orderInfor.order.payment_type).putExtra("status", orderInfor.order.status).putExtra("role", role).putExtra("remittance", new Gson().toJson(orderInfor.order.remittance)).putExtra("loan", new Gson().toJson(orderInfor.order.loan)));
                            }
                        });
                        ivNext.setVisibility(View.VISIBLE);
                    }
                    Picasso.with(ConfirmOrderActivity.this).load(result.order.getMerchant().getThumb()).error(R.drawable.shipping_shop).into(ivShop);
                    tvShopname.setText(result.order.getMerchant().getName());
                    List<OrderInfor.OrderBean.OrderGoodsBean> orderGoodsBeen = result.order.getOrder_goods();
                    for (OrderInfor.OrderBean.OrderGoodsBean orderGoodsBean : orderGoodsBeen) {
                        OrderInforGoodView orderInforGoodView = new OrderInforGoodView(ConfirmOrderActivity.this);
                        orderInforGoodView.setData(orderGoodsBean);
                        content.addView(orderInforGoodView);
                    }
                    tvPayWay.setText("支付方式: " + result.order.getPayment_type_name());
                    // 状态：-2已关闭 -1已驳回 1待付款 2待审核 3待发货 4待收货 5待评价 6已完成 ,

                    if(!TextUtils.isEmpty(result.order.pay_time)) {
                        tvPaytime.setVisibility(View.VISIBLE);
                        tvPaytime.setText("付款时间: "+result.order.pay_time);
                        line.setVisibility(View.VISIBLE);
                    }else {
                        tvPaytime.setVisibility(View.GONE);
                        line.setVisibility(View.GONE);
                    }
                    tvPrice.setText(String.valueOf("￥" + DisplayUtil.double2String(result.order.getTotal_money())));
                    tvFree.setText(String.valueOf("￥" + DisplayUtil.double2String(result.order.getCoupon_free_money())));
                    tvTotalmoney.setText(String.valueOf("￥" + DisplayUtil.double2String(result.order.getPay_money())));
                }
            }

            @Override
            public void onError(String errorCode, String message) {

            }

            @Override
            public void onFinished() {
                dismissDialog();
            }

            @Override
            public void onRefreshToken() {
                UserUtils.getInstance().goToLogin(ConfirmOrderActivity.this);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtil.printJ("onactivityresult");
        if (resultCode == RESULT_OK) {
            finish();
        }
    }


    private void dealWithOrder(final int role, final int status, int id) {
        BusinessManager.getInstance().dealWithOrder(new DealWithOrderRequest(role, status, id), new MyCallback<Void>() {
            @Override
            public void onSuccess(Void result, String message) {
                if (role == Constans.ORDERRECEIVE) {
                    switch (status) {
                        case 3:
                            showToast("提醒发货成功");
                            break;
                        case 4:
                            showToast("确认收货成功");
                            break;
                        case 7:
                            showToast("取消订单成功");
                            break;
                        case 8:
                            showToast("删除订单成功");
                            break;
                        default:
                            showToast(message);
                            break;
                    }
                } else {
                    switch (status) {
                        case 1:
                            showToast("提醒付款成功");
                            break;
                        case 4:
                            showToast("提醒收货成功");
                            break;
                        default:
                            showToast(message);
                            break;

                    }
                }
                if (role == Constans.ORDERRECEIVE) {
                    if (status == 4) {
                        EventBus.getDefault().post(new RefreshStatusMessage());
                    }
                }
                dismissDialog();
                finish();
            }

            @Override
            public void onError(String errorCode, String message) {
                showToast(message);
                dismissDialog();
            }

            @Override
            public void onFinished() {

            }

            @Override
            public void onRefreshToken() {
                UserUtils.getInstance().goToLogin(ConfirmOrderActivity.this);
            }
        });
    }


    private void doZFBzf(final String orderSN) {

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(
                        ConfirmOrderActivity.this);
                final Map<String, String> result = alipay
                        .payV2(orderSN, true);
                Log.i("msp", result.toString());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!TextUtils.isEmpty(result.get("memo"))) {
                            showToast(result.get("memo"));
                        }
                    }
                });
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void wxPay(WXpayEnity wXpayResult) {
        PayReq request = new PayReq();
        request.appId = wXpayResult.appid;
        request.partnerId = wXpayResult.partnerid;
        request.prepayId = wXpayResult.prepayid;
        request.packageValue = "Sign=WXPay";
        request.nonceStr = wXpayResult.noncestr;
        request.timeStamp = wXpayResult.timestamp;
        request.sign = wXpayResult.sign;
        iwxapi.registerApp(Constans.APP_ID);
        iwxapi.sendReq(request);
    }

    private void dpUPPay(String tn) {
        UPPayAssistEx.startPay(this, null, null, tn, "01");
    }
}
